package com.geaosu.niubiplus_java.utils.ImageLoader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 图片加载框架
 */
public class ImageLoader {
    // 监听器
    private OnImageLoadListener mOnImageLoadListener;
    // 缓存器 - 内存缓存
    private ImageCache mImageCache;
    // 缓存器 - SD卡缓存
    private DiskCache mDiskCache;
    // 缓存器 - SD卡缓存 - 开关
    private boolean mIsUseDiskCache = false;
    // 多线程加载
    private ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    // Handler
    private Handler mHandler = new Handler(Looper.getMainLooper());

    // 构造器
    public ImageLoader() {
        mImageCache = ImageCache.getDefault();
        mDiskCache = new DiskCache();
    }

    // 加载图片
    public void loadImage(String url, ImageView imageView) {
        Bitmap bitmap = mIsUseDiskCache ? mDiskCache.get(url.replace("/","-")) : mImageCache.get(url.replace("/","-"));
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            if (mOnImageLoadListener != null) {
                mOnImageLoadListener.onSucc(url, imageView, bitmap, "显示缓存图片");
            }
            return;
        }
        // 给view添加一个tag，tag唯一，后期根据tag更新view
        imageView.setTag(url);
        // 在子线程中下载图片
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                // 下载图片后，将图片的bitmap数据返回
                Bitmap bitmap = downloadImage(imageView, url);
                // 判断bitmap数据的完整性
                if (bitmap == null) {
                    return;
                }
                // 判断imageView和url是否匹配
                if (imageView.getTag().equals(url)) {
                    updataImageView(imageView, bitmap);
                }
                // 将图片的bitmap数据缓存起来
                if (mIsUseDiskCache) {
                    mDiskCache.put(url.replace("/","-"), bitmap);
                } else {
                    mImageCache.put(url.replace("/","-"), bitmap);
                }
            }
        });
    }

    // 下载文件
    private Bitmap downloadImage(ImageView imageView, String imgUrl) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(imgUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
            httpURLConnection.disconnect();
            if (mOnImageLoadListener != null) {
                mOnImageLoadListener.onSucc(imgUrl, imageView, bitmap, "图片下载成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (mOnImageLoadListener != null) {
                mOnImageLoadListener.onErr(imgUrl, imageView, e.toString());
            }
        }
        return bitmap;
    }

    // 在主线程更新UI
    private void updataImageView(ImageView imageView, Bitmap bitmap) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                imageView.setImageBitmap(bitmap);
            }
        });
    }

    /**
     * SD卡缓存开关
     *
     * @param isUseDiskCache
     */
    public void useDiskCache(boolean isUseDiskCache) {
        mIsUseDiskCache = isUseDiskCache;
    }

    /**
     * 设置加载监听器
     *
     * @param listener
     */
    public void setOnImageLoadListener(OnImageLoadListener listener) {
        mOnImageLoadListener = listener;
    }
}
